"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 数据库系统
Case Name   : 配置文件丢失恢复后，备机重建incremental模式
Create At   : 2020/07/27
@zou_jialiang0505328126
Description :
    1. 备机删除配置文件
    2. 备机进行增量重建
    3. 恢复配置文件
    4. 停止备机，主机建表并插入数据
    5. 备机再次进行增量重建
    6. 备机进行插入数据验证
Expect      :
    1. 备机删除配置文件
    2. 备机进行增量重建
    3. 恢复配置文件
    4. 停止备机，主机建表并插入数据
    5. 备机再次进行增量重建
    6. 备机进行插入数据验证
History     :
    modified：2021-3-24 by 5328113;备机增量重建失败，修改增量重建调用公共方法；修改整个用例逻辑
"""

import os
import time
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import *
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class Stop_immediate(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info("----this is setup----")
        self.common = Common()
        self.commonsh = CommonSH()
        self.constant = Constant()
        self.sta_dbuser = Node(node='Standby1DbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.sta_sh = CommonSH('Standby1DbUser')
        self.conf_file = os.path.join(macro.DB_INSTANCE_PATH,
                                      macro.DB_PG_CONFIG_NAME)
        self.conf_file_bak = self.conf_file + '.baktest'

        self.max_num = 1000
        self.table_test = 't_Dbsys_Case176'
        self.create_sql = f'drop table if exists {self.table_test};' \
            f'create table {self.table_test}(id int);'
        self.insert_sql = f'''begin 
            for i in 1..{self.max_num} loop
            insert into {self.table_test} values(i);
            end loop;
            end;'''
        self.select_sql = f'select count(*) from {self.table_test};'
        self.drop_sql = f'drop table {self.table_test};'

        self.log.info('----Opengauss_Reliability_Dbsys_Case176.py start----')

    def test_main(self):
        self.log.info("----刪除备机conf文件----")
        delete_cmd = f"cp -R {self.conf_file} {self.conf_file_bak};" \
            f"rm -rf {self.conf_file}"
        self.log.info(delete_cmd)
        self.sta_dbuser.sh(delete_cmd)
        ls_cmd = f'ls -al {self.conf_file}'
        self.log.info(self.sta_dbuser.sh(ls_cmd).result())

        self.log.info("----备机重建----")
        success_flag = self.constant.BUILD_SUCCESS_MSG
        build_result = self.sta_sh.executeGsctl('build',
                                                success_flag,
                                                '-b incremental')
        self.assertFalse(build_result)

        time.sleep(5)

        self.log.info("----恢复备机conf文件----")
        recover_cmd = f"cp -R {self.conf_file_bak} {self.conf_file}; " \
            f"rm -rf {self.conf_file_bak}"
        self.log.info(recover_cmd)
        self.sta_dbuser.sh(recover_cmd)
        ls_cmd = f'ls -al {self.conf_file}'
        self.log.info(self.sta_dbuser.sh(ls_cmd).result())

        self.log.info("----停止备机----")
        standby1_node_name = self.sta_dbuser.sh('cat /etc/hostname').result()
        self.log.info(standby1_node_name)
        stop_cmd = f'source {macro.DB_ENV_PATH};' \
            f'gs_om -t stop -h {standby1_node_name}'
        stop_msg = self.sta_dbuser.sh(stop_cmd).result()
        self.log.info(stop_msg)
        self.assertIn(self.constant.STOP_NODE_SUCCESS_MSG, stop_msg)

        self.log.info("----主机进行数据插入----")
        create_result = self.pri_sh.executDbSql(self.create_sql)
        self.log.info(create_result)
        insert_result = self.pri_sh.executDbSql(self.insert_sql)
        self.log.info(insert_result)
        select_result = self.pri_sh.executDbSql(self.select_sql)
        self.log.info(select_result)
        self.assertIn(str(self.max_num), select_result)

        self.log.info("----备机进行增量重建----")
        success_flag = self.constant.BUILD_SUCCESS_MSG
        build_result = self.sta_sh.executeGsctl('build',
                                                success_flag,
                                                '-b incremental')
        self.assertTrue(build_result)

        time.sleep(5)

        self.log.info("----备机进行插入数据验证----")
        select_result = self.sta_sh.executDbSql(self.select_sql)
        self.log.info(select_result)
        self.assertIn(str(self.max_num), select_result)

    def tearDown(self):
        self.log.info('----this is tearDown----')
        ls = self.sta_dbuser.sh(f'ls -al {macro.DB_INSTANCE_PATH}').result()
        if macro.DB_PG_CONFIG_NAME + '.baktest' in ls:
            self.log.info("----恢复备机conf文件----")
            recover_cmd = f'rm -f {self.conf_file}'
            self.log.info(recover_cmd)
            self.sta_dbuser.sh(recover_cmd)
            recover_cmd = f"cp -R {self.conf_file_bak} {self.conf_file}; " \
                f"rm -rf {self.conf_file_bak}"
            self.log.info(recover_cmd)
            self.sta_dbuser.sh(recover_cmd)

        self.log.info('----删除表----')
        drop_result = self.pri_sh.executDbSql(self.drop_sql)
        self.log.info(drop_result)
        self.log.info('----Opengauss_Reliability_Dbsys_Case176 执行完成----')
